import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ActivityIndicator,
  TouchableOpacity,
  Alert,
  ScrollView,
  PermissionsAndroid,
  Platform,
  TextInput,
} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import Clipboard from '@react-native-clipboard/clipboard';
import CardApiNative from '../services/CardApiNative';
import DouBaoTTSService from '../services/DouBaoTTSService';

const ServerInfoScreen: React.FC = () => {
  const [localIP, setLocalIP] = useState<string>('');
  const [serverPort, setServerPort] = useState<number>(8553);
  const [loading, setLoading] = useState(true);
  const [notificationPermission, setNotificationPermission] = useState<boolean>(false);
  const [foregroundServiceStatus, setForegroundServiceStatus] = useState<string>('未知');
  const [serverRunning, setServerRunning] = useState<boolean>(false);
  const [deviceName, setDeviceName] = useState<string>('');
  const [deviceModel, setDeviceModel] = useState<string>('');
  const [isEditingName, setIsEditingName] = useState<boolean>(false);
  const [editingName, setEditingName] = useState<string>('');
  const [ttsAppId, setTtsAppId] = useState<string>('');
  const [ttsToken, setTtsToken] = useState<string>('');
  const [isEditingTTS, setIsEditingTTS] = useState<boolean>(false);
  const [editingTtsAppId, setEditingTtsAppId] = useState<string>('');
  const [editingTtsToken, setEditingTtsToken] = useState<string>('');

  useEffect(() => {
    getLocalIP();
    checkPermissions();
    checkServerStatus();
    getDeviceInfo();
    getTTSConfig();
  }, []);

  const getLocalIP = async () => {
    try {
      setLoading(true);
      const ip = await CardApiNative.getLocalIPAddress();
      setLocalIP(ip);
      console.log('本机局域网 IP 获取成功:', ip);
    } catch (error) {
      console.error('获取本机 IP 失败:', error);
      setLocalIP('127.0.0.1');
      Alert.alert('错误', '获取局域网 IP 失败');
    } finally {
      setLoading(false);
    }
  };

  const checkPermissions = async () => {
    try {
      if (Platform.OS === 'android' && Platform.Version >= 33) {
        // Android 13+ 需要请求通知权限
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
          {
            title: '通知权限',
            message: 'BabyTapMobile 需要通知权限来显示前台服务状态',
            buttonNeutral: '稍后询问',
            buttonNegative: '拒绝',
            buttonPositive: '允许',
          }
        );
        
        const hasPermission = granted === PermissionsAndroid.RESULTS.GRANTED;
        setNotificationPermission(hasPermission);
        console.log('通知权限状态:', hasPermission ? '已授予' : '未授予');
        
        if (!hasPermission) {
          Alert.alert(
            '通知权限未授予',
            '请在系统设置中手动启用 BabyTapMobile 的通知权限，否则前台服务可能无法正常工作。',
            [
              { text: '知道了', style: 'default' },
              { text: '去设置', onPress: () => {
                // 这里可以添加跳转到应用设置的逻辑
                console.log('引导用户去设置');
              }}
            ]
          );
        }
      } else {
        // Android 13 以下版本不需要特殊权限
        setNotificationPermission(true);
      }
    } catch (error) {
      console.error('检查权限失败:', error);
      setNotificationPermission(false);
    }
  };

  const checkServerStatus = async () => {
    try {
      // 检查服务器是否正在运行
      const isStarted = CardApiNative.isServerStarted();
      setServerRunning(isStarted);
      setForegroundServiceStatus(isStarted ? '运行中' : '未运行');
      
      console.log('服务器状态:', isStarted ? '运行中' : '未运行');
    } catch (error) {
      console.error('检查服务器状态失败:', error);
      setServerRunning(false);
      setForegroundServiceStatus('检查失败');
    }
  };

  const getDeviceInfo = async () => {
    try {
      // 获取设备型号
      const model = await CardApiNative.getDeviceModel();
      setDeviceModel(model);
      
      // 获取当前设备名称
      const name = await CardApiNative.getDeviceName();
      setDeviceName(name);
      setEditingName(name);
      
      console.log('设备信息获取成功:', { model, name });
    } catch (error) {
      console.error('获取设备信息失败:', error);
      setDeviceModel('未知设备');
      setDeviceName('BabyTap手机');
      setEditingName('BabyTap手机');
    }
  };

  const handleSaveDeviceName = async () => {
    try {
      if (editingName.trim() === '') {
        Alert.alert('错误', '设备名称不能为空');
        return;
      }

      await CardApiNative.setDeviceName(editingName.trim());
      setDeviceName(editingName.trim());
      setIsEditingName(false);
      
      Alert.alert('成功', '设备名称设置成功');
    } catch (error) {
      console.error('设置设备名称失败:', error);
      Alert.alert('错误', '设置设备名称失败: ' + (error instanceof Error ? error.message : String(error)));
    }
  };

  const getTTSConfig = async () => {
    try {
      // 先从本地存储读取
      const storedConfig = await AsyncStorage.getItem('tts_config');
      if (storedConfig) {
        const config = JSON.parse(storedConfig);
        setTtsAppId(config.appid || '');
        setTtsToken(config.token || '');
        setEditingTtsAppId(config.appid || '');
        setEditingTtsToken(config.token || '');
        console.log('从本地存储读取TTS配置成功:', config);
        
        // 同时设置到Native模块
        await DouBaoTTSService.setTTSConfig(config.appid || '', config.token || '');
      }
      
      // 再从Native模块读取（作为备份）
      const nativeConfig = await DouBaoTTSService.getTTSConfig();
      if (nativeConfig.appid && nativeConfig.token) {
        setTtsAppId(nativeConfig.appid);
        setTtsToken(nativeConfig.token);
        setEditingTtsAppId(nativeConfig.appid);
        setEditingTtsToken(nativeConfig.token);
        console.log('从Native模块读取TTS配置成功:', nativeConfig);
      }
    } catch (error) {
      console.error('TTS配置获取失败:', error);
      setTtsAppId('');
      setTtsToken('');
      setEditingTtsAppId('');
      setEditingTtsToken('');
    }
  };

  const handleSaveTTSConfig = async () => {
    try {
      if (editingTtsAppId.trim() === '' || editingTtsToken.trim() === '') {
        Alert.alert('错误', 'AppID和Token不能为空');
        return;
      }

      const config = {
        appid: editingTtsAppId.trim(),
        token: editingTtsToken.trim()
      };

      // 保存到本地存储
      await AsyncStorage.setItem('tts_config', JSON.stringify(config));
      
      // 保存到Native模块
      await DouBaoTTSService.setTTSConfig(config.appid, config.token);
      
      setTtsAppId(config.appid);
      setTtsToken(config.token);
      setIsEditingTTS(false);
      
      Alert.alert('成功', 'TTS配置已保存');
    } catch (error) {
      console.error('保存TTS配置失败:', error);
      Alert.alert('错误', '保存TTS配置失败: ' + (error instanceof Error ? error.message : String(error)));
    }
  };

  const copyToClipboard = (text: string, label: string) => {
    Clipboard.setString(text);
    Alert.alert('复制成功', `${label} 已复制到剪贴板`);
  };

  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#4a90e2" />
        <Text style={styles.loadingText}>正在获取服务器信息...</Text>
      </View>
    );
  }

  return (
    <ScrollView style={styles.container}>
      <View style={styles.content}>
        {/* 服务器状态 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>服务器状态</Text>
          <View style={styles.statusCard}>
            <View style={styles.statusRow}>
              <Text style={styles.statusLabel}>前台服务</Text>
              <View style={styles.statusIndicator}>
                <View style={[styles.statusDot, serverRunning ? styles.statusDotSuccess : styles.statusDotError]} />
                <Text style={[styles.statusText, serverRunning ? styles.statusTextSuccess : styles.statusTextError]}>
                  {foregroundServiceStatus}
                </Text>
              </View>
            </View>
            <View style={styles.statusRow}>
              <Text style={styles.statusLabel}>通知权限</Text>
              <View style={styles.statusIndicator}>
                <View style={[styles.statusDot, notificationPermission ? styles.statusDotSuccess : styles.statusDotError]} />
                <Text style={[styles.statusText, notificationPermission ? styles.statusTextSuccess : styles.statusTextError]}>
                  {notificationPermission ? '已授予' : '未授予'}
                </Text>
              </View>
            </View>
          </View>
        </View>

        {/* 网络信息 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>网络信息</Text>
          <View style={styles.infoCard}>
            <View style={styles.infoRow}>
              <Text style={styles.infoLabel}>局域网地址</Text>
              <TouchableOpacity 
                style={styles.infoValueContainer}
                onPress={() => copyToClipboard(localIP, '局域网地址')}
              >
                <Text style={styles.infoValue}>{localIP}</Text>
                <Text style={styles.copyHint}>点击复制</Text>
              </TouchableOpacity>
            </View>
            <View style={styles.infoRow}>
              <Text style={styles.infoLabel}>端口</Text>
              <TouchableOpacity 
                style={styles.infoValueContainer}
                onPress={() => copyToClipboard(serverPort.toString(), '端口')}
              >
                <Text style={styles.infoValue}>{serverPort}</Text>
                <Text style={styles.copyHint}>点击复制</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>

        {/* 设备信息 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>设备信息</Text>
          <View style={styles.infoCard}>
            <View style={styles.infoRow}>
              <Text style={styles.infoLabel}>设备型号</Text>
              <Text style={styles.infoValue}>{deviceModel}</Text>
            </View>
            <View style={styles.infoRow}>
              <Text style={styles.infoLabel}>设备名称</Text>
              {isEditingName ? (
                <View style={styles.editContainer}>
                  <TextInput
                    style={styles.editInput}
                    value={editingName}
                    onChangeText={setEditingName}
                    placeholder="输入设备名称"
                    autoFocus
                  />
                  <TouchableOpacity 
                    style={styles.saveButton}
                    onPress={handleSaveDeviceName}
                  >
                    <Text style={styles.saveButtonText}>保存</Text>
                  </TouchableOpacity>
                  <TouchableOpacity 
                    style={styles.cancelButton}
                    onPress={() => {
                      setIsEditingName(false);
                      setEditingName(deviceName);
                    }}
                  >
                    <Text style={styles.cancelButtonText}>取消</Text>
                  </TouchableOpacity>
                </View>
              ) : (
                <TouchableOpacity 
                  style={styles.infoValueContainer}
                  onPress={() => setIsEditingName(true)}
                >
                  <Text style={styles.infoValue}>{deviceName}</Text>
                  <Text style={styles.editHint}>点击编辑</Text>
                </TouchableOpacity>
              )}
            </View>
          </View>
        </View>

        {/* TTS配置 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>语音合成配置</Text>
          <View style={styles.infoCard}>
            <View style={styles.infoRow}>
              <Text style={styles.infoLabel}>AppID</Text>
              {isEditingTTS ? (
                <View style={styles.editContainer}>
                  <TextInput
                    style={styles.editInput}
                    value={editingTtsAppId}
                    onChangeText={setEditingTtsAppId}
                    placeholder="输入AppID"
                    autoFocus
                  />
                </View>
              ) : (
                <TouchableOpacity 
                  style={styles.infoValueContainer}
                  onPress={() => setIsEditingTTS(true)}
                >
                  <Text style={styles.infoValue}>{ttsAppId || '未设置'}</Text>
                  <Text style={styles.editHint}>点击编辑</Text>
                </TouchableOpacity>
              )}
            </View>
            <View style={styles.infoRow}>
              <Text style={styles.infoLabel}>Token</Text>
              {isEditingTTS ? (
                <View style={styles.editContainer}>
                  <TextInput
                    style={styles.editInput}
                    value={editingTtsToken}
                    onChangeText={setEditingTtsToken}
                    placeholder="输入Token"
                    secureTextEntry
                  />
                  <TouchableOpacity 
                    style={styles.saveButton}
                    onPress={handleSaveTTSConfig}
                  >
                    <Text style={styles.saveButtonText}>保存</Text>
                  </TouchableOpacity>
                  <TouchableOpacity 
                    style={styles.cancelButton}
                    onPress={() => {
                      setIsEditingTTS(false);
                      setEditingTtsAppId(ttsAppId);
                      setEditingTtsToken(ttsToken);
                    }}
                  >
                    <Text style={styles.cancelButtonText}>取消</Text>
                  </TouchableOpacity>
                </View>
              ) : (
                <TouchableOpacity 
                  style={styles.infoValueContainer}
                  onPress={() => setIsEditingTTS(true)}
                >
                  <Text style={styles.infoValue}>{ttsToken ? '••••••••••' : '未设置'}</Text>
                  <Text style={styles.editHint}>点击编辑</Text>
                </TouchableOpacity>
              )}
            </View>
          </View>
        </View>

        {/* 访问地址 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>访问地址</Text>
          <View style={styles.infoCard}>
            <View style={styles.infoRow}>
              <Text style={styles.infoLabel}>完整地址</Text>
              <TouchableOpacity 
                style={styles.infoValueContainer}
                onPress={() => copyToClipboard(`https://${localIP}:${serverPort}`, '完整地址')}
              >
                <Text style={styles.infoValue}>
                  https://{localIP}:{serverPort}
                </Text>
                <Text style={styles.copyHint}>点击复制</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>

        {/* 使用说明 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>使用说明</Text>
          <View style={styles.instructionCard}>
            <Text style={styles.instructionText}>
              1. 确保您的设备和其他设备在同一个局域网内
            </Text>
            <Text style={styles.instructionText}>
              2. 在电视上安装 宝宝点读卡电视版 应用
            </Text>
            <Text style={styles.instructionText}>
              3. 电视版会自动发现并连接到此设备
            </Text>
            <Text style={styles.instructionText}>
              4. 在手机上管理卡片，电视上实时显示学习
            </Text>
          </View>
        </View>

        {/* 刷新按钮 */}
        <TouchableOpacity style={styles.refreshButton} onPress={() => {
          getLocalIP();
          checkPermissions();
          checkServerStatus();
          getDeviceInfo();
          getTTSConfig();
        }}>
          <Text style={styles.refreshButtonText}>刷新所有信息</Text>
        </TouchableOpacity>
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#f5f5f5',
  },
  loadingText: {
    color: '#666',
    fontSize: 16,
    marginTop: 16,
  },
  content: {
    padding: 16,
  },
  section: {
    marginBottom: 24,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 12,
  },
  statusCard: {
    backgroundColor: '#ffffff',
    borderRadius: 12,
    padding: 16,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  statusRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  statusLabel: {
    fontSize: 16,
    color: '#666',
    fontWeight: '500',
  },
  statusIndicator: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  statusDot: {
    width: 8,
    height: 8,
    borderRadius: 4,
    backgroundColor: '#4CAF50',
    marginRight: 8,
  },
  statusDotSuccess: {
    backgroundColor: '#4CAF50',
  },
  statusDotError: {
    backgroundColor: '#F44336',
  },
  statusText: {
    fontSize: 16,
    color: '#4CAF50',
    fontWeight: 'bold',
  },
  statusTextSuccess: {
    color: '#4CAF50',
  },
  statusTextError: {
    color: '#F44336',
  },
  infoCard: {
    backgroundColor: '#ffffff',
    borderRadius: 12,
    padding: 16,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  infoRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  infoLabel: {
    fontSize: 16,
    color: '#666',
    fontWeight: '500',
    flex: 1,
  },
  infoValueContainer: {
    flex: 2,
    alignItems: 'flex-end',
  },
  infoValue: {
    fontSize: 16,
    color: '#4a90e2',
    fontWeight: 'bold',
    textAlign: 'right',
  },
  copyHint: {
    fontSize: 12,
    color: '#999',
    marginTop: 2,
  },
  instructionCard: {
    backgroundColor: '#ffffff',
    borderRadius: 12,
    padding: 16,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  instructionText: {
    fontSize: 14,
    color: '#666',
    lineHeight: 20,
    marginBottom: 8,
  },
  refreshButton: {
    backgroundColor: '#4a90e2',
    paddingVertical: 16,
    borderRadius: 12,
    alignItems: 'center',
    marginTop: 16,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  refreshButtonText: {
    color: '#ffffff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  editContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 2,
  },
  editInput: {
    flex: 1,
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 6,
    paddingHorizontal: 8,
    paddingVertical: 4,
    fontSize: 16,
    color: '#333',
    marginRight: 8,
  },
  saveButton: {
    backgroundColor: '#4CAF50',
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 6,
    marginRight: 4,
  },
  saveButtonText: {
    color: '#ffffff',
    fontSize: 14,
    fontWeight: 'bold',
  },
  cancelButton: {
    backgroundColor: '#F44336',
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 6,
  },
  cancelButtonText: {
    color: '#ffffff',
    fontSize: 14,
    fontWeight: 'bold',
  },
  editHint: {
    fontSize: 12,
    color: '#999',
    marginTop: 2,
  },
});

export default ServerInfoScreen; 